import Cookies from 'js-cookie'
import website from '@/config/website'

const TokenKey = website.key + '-access-token'
const TokenConfigKey = website.key + '-token-config'
const SsoTokenKey = website.key + '-access-ssotoken'
let tokenConfigObj = null

export function getTokenConfig() {
  return localStorage.getItem(TokenConfigKey)
}
export function getTokenConfigObj() {
  if (tokenConfigObj && tokenConfigObj.tokenName) return tokenConfigObj
  try {
    tokenConfigObj = JSON.parse(getTokenConfig())
  } catch (error) {
    console.error(error)
    tokenConfigObj = {}
  }
  return tokenConfigObj
}

export function getTokenKey() {
  return getTokenConfigObj().tokenName
}
export function getTokenPrefix() {
  return getTokenConfigObj().tokenPrefix
}

export function setTokenConfig(config) {
  tokenConfigObj = config || ''
  localStorage.setItem(TokenConfigKey, (tokenConfigObj && JSON.stringify(tokenConfigObj)) || '')
}
export function removeTokenConfig() {
  localStorage.removeItem(TokenConfigKey)
}
// 清除sessionStorage 某个key
export function removeSessionItem(itemKey) {
  sessionStorage.removeItem(itemKey)
}
// 清除所有sessionStorage值
export function removeAllSession() {
  sessionStorage.clear()
}
export function getToken() {
  return Cookies.get(TokenKey)
}

export function setToken(token) {
  return Cookies.set(TokenKey, token)
}

export function removeToken() {
  return Cookies.remove(TokenKey)
}

export function getSsoToken() {
  return Cookies.get(SsoTokenKey)
}

export function setSsoToken(token) {
  return Cookies.set(SsoTokenKey, token)
}

export function removeSsoToken() {
  return Cookies.remove(SsoTokenKey)
}

// 逃生通道
export function getSosWay() {
  const tokenData = getTokenConfigObj().tokenData
  return tokenData && tokenData.sosWay
}

/**
 * 获取单个cookie
 * @param {*} key 属性
 * @returns cookie属性对应的值
 */
export function getTheKeyCookie(key) {
  return Cookies.get(key)
}
/**
 * 设置单个cookie
 * @param {*} key 属性
 * @param {*} value 值
 */
export function setCookie(key, value) {
  Cookies.set(key, value)
}
/**
 * 删除cookie下某个属性
 * @param {*} key 属性
 */
export function deleteCookie(key) {
  Cookies.remove(key)
}
export function deleteTokenCookie() {
  const tokenConfig = JSON.parse(getTokenConfig())
  deleteCookie(tokenConfig.tokenName)
  clearAllCookie()
}

/**
 * 删除所有cookie
 */
export function clearAllCookie() {
  removeToken()
  // removeSsoToken()
}
const clearAllStorage = storage => {
  Object.keys(storage).forEach(key => {
    // 调用sosWay会返回401，此时需要保留token-config
    if (key.startsWith(website.key) && !key.startsWith(website.key + '-token-config')) {
      storage.removeItem(key)
    }
  })
}
export function clearAllLocalStorage() {
  clearAllStorage(localStorage)
}
export function clearAllSessionStorage() {
  clearAllStorage(sessionStorage)
}
export function cleanAllCash() {
  clearAllCookie()
  clearAllLocalStorage()
  clearAllSessionStorage()
}
